package com.ransj.iphone.view;

import com.ransj.iphone.IKey;
import com.ransj.iphone.IKeyListener;
import com.ransj.iphone.R;
import com.ransj.iphone.R.id;
import com.ransj.iphone.R.layout;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;

/**
 * nine pad view
 * 
 * @author ranshengju
 * 
 */
public class NinePad extends AbsView implements OnClickListener {
	private int[] mKeyCode;

	private NinePad(Context context, int[] res) {
		mMainView = LayoutInflater.from(context).inflate(
				R.layout.iphone_key_pad, null);
		mMainView.findViewById(R.id.key_pad).setOnClickListener(this);
		mMainView.findViewById(R.id.key_pad_rect).setOnClickListener(this);
		initItems(res);
	}
	
	private void initItems(int[] res){
		generateItem(R.id.key_pad_item_0, res[0]);
		generateItem(R.id.key_pad_item_1, res[1]);
		generateItem(R.id.key_pad_item_2, res[2]);
		generateItem(R.id.key_pad_item_3, res[3]);
		generateItem(R.id.key_pad_item_4, res[4]);
		generateItem(R.id.key_pad_item_5, res[5]);
		generateItem(R.id.key_pad_item_6, res[6]);
		generateItem(R.id.key_pad_item_7, res[7]);
		generateItem(R.id.key_pad_item_8, res[8]);
		
	}

	private void generateItem(int id, int bg) {
		View item = mMainView.findViewById(id);
		if (item != null && bg != -1) {
			item.setOnClickListener(this);
			item.setBackgroundResource(bg);
		}
	}

	public void onClick(View v) {
		int keycode = -1;
		switch (v.getId()) {
		case R.id.key_pad:
			keycode = IKey.KEY_PAD_OUTSIDE;
			break;
		case R.id.key_pad_item_0:
			keycode = mKeyCode[0];
			break;
		case R.id.key_pad_item_1:
			keycode = mKeyCode[1];
			break;
		case R.id.key_pad_item_2:
			keycode = mKeyCode[2];
			break;
		case R.id.key_pad_item_3:
			keycode = mKeyCode[3];
			break;
		case R.id.key_pad_item_4:
			keycode = mKeyCode[4];
			break;
		case R.id.key_pad_item_5:
			keycode = mKeyCode[5];
			break;
		case R.id.key_pad_item_6:
			keycode = mKeyCode[6];
			break;
		case R.id.key_pad_item_7:
			keycode = mKeyCode[7];
			break;
		case R.id.key_pad_item_8:
			keycode = mKeyCode[8];
			break;
		}
		if (mKeyListener != null && keycode != -1) {
			mKeyListener.onKeyEvent(this, keycode);
		}
	}

	public static NinePad createPad(Context context, int[] res, int[] keys,
			IKeyListener listener, LayoutParams params) {
		NinePad temp = new NinePad(context, res);
		temp.mKeyCode = keys;
		temp.mKeyListener = listener;
		temp.mWMParams = params;
		return temp;
	}
	
	public void refresh(int[] res, int[] keys){
		mKeyCode = keys;
		initItems(res);
	}

}
